package com.jpxx.netty.hello;

import io.netty.bootstrap.Bootstrap;  
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;  
import io.netty.channel.ChannelInitializer;  
import io.netty.channel.ChannelOption;  
import io.netty.channel.ChannelPipeline;  
import io.netty.channel.EventLoopGroup;  
import io.netty.channel.nio.NioEventLoopGroup;  
import io.netty.channel.socket.SocketChannel;  
import io.netty.channel.socket.nio.NioSocketChannel;  
import io.netty.handler.codec.string.StringDecoder;  
import io.netty.handler.codec.string.StringEncoder;  
  
public class Client {  
      
  
    public static void main(String[] args) throws Exception {  
  
        // Configure the client. 只需要1个线程组  
    	//一个服务端可以有多个客户端连接，但是客户端只需要一个服务端给响应
        EventLoopGroup clientGroup = new NioEventLoopGroup();
        try {  
            Bootstrap bootstrap = new Bootstrap();  
            bootstrap.group(clientGroup)  
            //服务端是NioServerSocketChannel，此处是NioSocketChannel
             .channel(NioSocketChannel.class)  // 指定客户端模式
             .option(ChannelOption.TCP_NODELAY, true)
             .handler(new ChannelInitializer<SocketChannel>() {  
                 @Override  
                 public void initChannel(SocketChannel sc) throws Exception {  
                     //sc.pipeline().addLast("decoder", new StringDecoder());//字符集
                     //sc.pipeline().addLast("encoder", new StringEncoder());  
                     sc.pipeline().addLast(new ClientHandler());  
                 }  
             });  
            
            
            ChannelFuture channelFuture = bootstrap.connect("127.0.0.1",2555).sync();//连接服务端的地方
            //连接成功
            System.out.println("client   127.0.0.1:2555 连接上~~~~~~~~~~~");
            
            for (int i = 0; i <5; i++) {
            	String res ="你好Netty服务器 ,我是客户端第"+(i+1)+"次给你发数据。"; 
            	
            	channelFuture.channel().writeAndFlush(Unpooled.copiedBuffer(res.getBytes()));
      			Thread.sleep(1000);
			}
            
            channelFuture.channel().closeFuture().sync();
        } finally {  
        	clientGroup.shutdownGracefully();  
        }  
    }  
  
}  